<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\RlMember;
use plugin\admin\app\model\RlOrder;
use support\Request;
use support\Response;
use plugin\admin\app\model\RlOrderInvoice;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 发票管理 
 */
class RlOrderInvoiceController extends Crud
{
    
    /**
     * @var RlOrderInvoice
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new RlOrderInvoice;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('rl-order-invoice/index');
    }

    /**
     * 获取
     * @return Response
     */
    public function select(Request $request): Response
    {
        $page = (int)$request->get('page');
        $limit = (int)$request->get('limit', 10);
        $where['status']=1;
        if ($id=$request->get('id','')){
            $where['_id']=$id;
        }
        $count=RlOrderInvoice::count();
        $offset=($page-1)*$limit;
        $lists= RlOrderInvoice::orderBy('id','desc')
            ->offset($offset)->limit($limit)->get()->toArray();
        //获取用户ID
        $memberIds=array_column($lists,'member_id');
        $members=RlMember::whereIn('id',$memberIds)->get()->toArray();
        $members=array_column($members,null,'id');
        //获取订单ID组
        $orderIds=array_column($lists,'order_id');
        $orders=RlOrder::whereIn('id',$orderIds)->get()->toArray();
        $orders=array_column($orders,null,'id');
        //进行昵称头像追加
        foreach ($lists as &$list){
            $list['nickname']=$members[$list['member_id']]['nickname']??'';
            $list['avatar']=$members[$list['member_id']]['avatar']??'';
            $list['order_sn']=$orders[$list['order_id']]['order_sn']??'';
        }
        return json(['code' => 0, 'data' => $lists, 'count'=>$count,'msg' => '成功']);
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('rl-order-invoice/update');
    }

}
